-
Notifications
You must be signed in to change notification settings - Fork 0
/
Disjoint Set - (Union by size).cpp
53 lines (46 loc) · 1.15 KB
/
Disjoint Set - (Union by size).cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <vector>
using namespace std;
class Graph {
private:
vector <int> parent;
vector <int> size;
public:
Graph(int n){ // Constructor
parent = vector<int>(n+1);
size = vector<int>(n+1, 1);
for(int i = 0; i <= n; i++)
parent[i] = i;
}
int find_parent(int key){
if(key == parent[key]) return key;
return parent[key] = find_parent(parent[key]);
}
void make_union(int u, int v){ // Union By Size
int pu = find_parent(u), pv = find_parent(v);
if(size[pu] < size[pv]){
parent[pu] = pv;
size[pv] += size[pu];
} else {
parent[pv] = pu;
size[pu] = size[pv];
}
}
void isDisjoint(int u, int v){
if(find_parent(u) != find_parent(v)){
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
}
};
int main(){
Graph G(10);
G.make_union(1, 2);
G.make_union(2, 3);
G.make_union(4, 5);
G.make_union(5, 6);
// Check disjoint sets
cout << "{1, 3}: "; G.isDisjoint(1, 3);
cout << "{1, 6}: "; G.isDisjoint(1, 6);
}